<script setup lang="ts">
import { Document, Monitor, Operation, Setting, Star, Tools } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { routes as appRoutes } from './router/index'
import { useAppStore } from './stores/app'
import 'dayjs/locale/zh-cn'

// 配置 dayjs 中文
dayjs.locale('zh-cn')

const appStore = useAppStore()
const isDark = ref(false)
const appInfo = ref<any>(null)
const connectionStatus = ref('已连接')
const currentJob = ref<any>(null)
const currentTime = ref('')
const isDev = import.meta.env.DEV

// 侧边菜单：基于路由动态生成
const iconMap: Record<string, any> = {
  Document,
  Monitor,
  Operation,
  Setting,
  Star,
  Tools, // 作为 Robot 的映射
  Robot: Tools,
}
function getIcon(name?: string) {
  return (name && iconMap[name]) || Document
}
const menuRoutes = computed(() => {
  const list = appRoutes.filter(r => !r.redirect && r.meta?.title && !r.meta?.deprecated && r.path && !String(r.path).includes(':') && String(r.path) !== '/config')
  return list.slice().sort((a, b) => {
    const ao = (a.meta as any)?.order ?? 9999
    const bo = (b.meta as any)?.order ?? 9999
    if (ao !== bo)
      return ao - bo
    const at = String((a.meta as any)?.title || '')
    const bt = String((b.meta as any)?.title || '')
    return at.localeCompare(bt)
  })
})

// 更新时间
function updateTime() {
  currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
}

// 主题切换
function toggleTheme(dark: boolean) {
  document.documentElement.classList.toggle('dark', dark)
  localStorage.setItem('theme', dark ? 'dark' : 'light')
}

// 初始化主题
function initTheme() {
  // 生产环境禁用主题切换，强制浅色
  if (import.meta.env.PROD) {
    isDark.value = false
    toggleTheme(false)
    return
  }
  const savedTheme = localStorage.getItem('theme')
  isDark.value = savedTheme === 'dark'
  toggleTheme(isDark.value)
}

// 获取应用信息
async function getAppInfo() {
  try {
    const result = await window.api.system.getAppInfo()
    if (result.success) {
      appInfo.value = result.data
    }
  }
  catch (error) {
    console.error('获取应用信息失败:', error)
  }
}

// 监听任务状态
async function monitorJobStatus() {
  try {
    const result = await window.api.script.status({})
    if (result.success && result.jobs.length > 0) {
      const runningJob = result.jobs.find(job => job.status === 'running')
      currentJob.value = runningJob || null
    }
  }
  catch (error) {
    console.error('获取任务状态失败:', error)
  }
}

// 定时器
let timeTimer: ReturnType<typeof setInterval>
let jobTimer: ReturnType<typeof setInterval>

onMounted(async () => {
  // 初始化主题
  initTheme()

  // 获取应用信息
  await getAppInfo()

  // 启动定时器
  updateTime()
  timeTimer = setInterval(updateTime, 1000)
  jobTimer = setInterval(monitorJobStatus, 2000)

  // 初始化应用状态
  await appStore.initialize()

  console.log('✅ 应用初始化完成')
})

onUnmounted(() => {
  if (timeTimer)
    clearInterval(timeTimer)
  if (jobTimer)
    clearInterval(jobTimer)
})

// 全局错误处理
window.addEventListener('error', (event) => {
  try {
    // 尽可能输出更多上下文，便于定位（某些情况下 event.error 可能为 null）
    const info = {
      message: (event as any).message || '',
      filename: (event as any).filename || '',
      lineno: (event as any).lineno || '',
      colno: (event as any).colno || '',
      error: (event as any).error || null,
      stack: (event as any).error?.stack || '',
    }
    console.error('应用错误:', info)
  }
  catch {
    console.error('应用错误:', event.error)
  }
  ElMessage.error('应用发生错误，请查看控制台')
})

window.addEventListener('unhandledrejection', (event) => {
  try {
    const reason = (event as any).reason
    const info = typeof reason === 'object' && reason
      ? { message: (reason as any).message, stack: (reason as any).stack }
      : { message: String(reason) }
    console.error('未处理的 Promise 拒绝:', info)
  }
  catch {
    console.error('未处理的 Promise 拒绝:', (event as any).reason)
  }
  ElMessage.error('应用发生异步错误，请查看控制台')
})
</script>

<template>
  <div id="app" class="h-screen flex flex-col overflow-hidden">
    <!-- 顶部导航栏 -->
    <el-header class="flex items-center justify-between border-b bg-white px-4">
      <div class="flex items-center space-x-4">
        <h1 class="text-xl text-gray-800 font-bold">
          预约辅助工具
        </h1>
        <el-tag v-if="appInfo" type="info" size="small">
          v{{ appInfo.version }}
        </el-tag>
      </div>

      <div class="flex items-center space-x-2">
        <!-- 主题切换：仅开发环境显示 -->
        <el-switch
          v-if="isDev"
          v-model="isDark"
          inline-prompt
          active-icon="Moon"
          inactive-icon="Sunny"
          @change="toggleTheme"
        />

        <!-- 设置按钮 -->
        <el-button circle @click="$router.push('/config')">
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </el-header>

    <!-- 主体内容 -->
    <el-container class="min-h-0 flex-1 overflow-hidden">
      <!-- 侧边导航 -->
      <el-aside width="200px" class="h-full overflow-auto border-r bg-gray-50">
        <el-menu
          :default-active="$route.path"
          router
          class="h-full border-none"
        >
          <el-menu-item
            v-for="route in menuRoutes"
            :key="route.path"
            :index="route.path as string"
          >
            <el-icon>
              <component :is="getIcon(route.meta?.icon as string)" />
            </el-icon>
            <span>{{ route.meta?.title }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 页面内容 -->
      <el-main class="overflow-auto p-6">
        <router-view />
      </el-main>
    </el-container>

    <!-- 底部状态栏 -->
    <el-footer height="40px" class="flex flex-shrink-0 items-center justify-between bg-gray-100 px-4 text-sm text-gray-600">
      <div class="flex items-center space-x-4">
        <span>状态: {{ connectionStatus }}</span>
        <span v-if="currentJob">任务: {{ currentJob.current_step }} ({{ currentJob.progress }}%)</span>
      </div>
      <div class="flex items-center space-x-2">
        <span>{{ currentTime }}</span>
      </div>
    </el-footer>
  </div>
</template>

<style scoped>
/* 自定义样式 */
.el-header {
  --el-header-padding: 0;
}

.el-aside {
  --el-aside-padding: 0;
}

.el-main {
  --el-main-padding: 0;
}

.el-footer {
  --el-footer-padding: 0;
  border-top: 1px solid var(--el-border-color-light);
}
</style>
